<template>
  <section class='f-card-detail'>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="overflow-y: auto;flex:1">
      <section class="f-phone-box">
        <p class="f-iccid">{{formData.code || '--'}}
          <img src="@/assets/icons/btn_icon_copy_white.png" alt="" @click="handleCopy(formData.code)">
        </p>
        <section class="f-box">
          <div class="f-flow">
            <p style="font-weight: 300;font-size: 9px;">本月剩余</p>
            <p class="f-mt-05">{{ bytesToSize(formData.remain)}}</p>
          </div>
        </section>
        <section class="f-btn-box">
          <p @click="pageJump('/meal')">订购套餐</p>
        </section>
      </section>

      <section class="f-network-box">
        <div class="f-title">
          <span>点击运营商，尝试使用其它网络</span>
          <p v-if="isConnect" style="color:#3050ED">已连接</p>
          <van-button v-else type="warning" size="small" plain round @click="openDevice">
            <div style="display: flex;align-items: center;">
              <img class="f-mr-05" style="width: 11px;" src="@/assets/icons/home_icon_ununited.png" alt="">
              <span>去连接</span>
            </div>
          </van-button>
        </div>

        <ul class="f-ul">
          <li class="f-li" v-for="(myItem,myIndex) in formData.cardIspList" :key="myIndex"
            :class="{'f-li-active': ispName[currentOperatorName] == ispName[myItem.isp]}" @click="checkChangeOperator(myItem)">
            <div class="g-flex-ct" style="height: 10px;">
              <img v-if="myItem.isp == 'unicom'" style="width: 21px;margin-left: 11px;" src="@/assets/icons/icon_liantong.png"
                alt="">
              <img v-if="myItem.isp == 'cmcc'" style="width: 21px;margin-left: 11px;" src="@/assets/icons/icon_yidong.png" alt="">
              <img v-if="myItem.isp == 'cbn'" style="width: 21px;margin-left: 11px;" src="@/assets/icons/icon_guangdian.png"
                alt="">
              <img v-if="myItem.isp == 'telecom'" class="f-img" src="@/assets/icons/icon_dianxin.png" alt="">
              <p class="f-ml-05">中国{{myItem.ispName}}</p>
            </div>
            <div class="f-center" style="margin-top: 7px;">
              <span class="f-real-name" :style="{'background': myItem.isRealName == 1? '#304EEE': ''}">
                {{myItem.isRealName == 1? '已实名': '未实名'}}
              </span>
            </div>
          </li>
        </ul>

        <div class="f-cell">
          <p>当前服务</p>
          <p>{{currentOperatorName? ispName[currentOperatorName]: '--'}}</p>
        </div>
        <div class="f-cell">
          <p>设备型号</p>
          <p>{{formData.devModel || '--'}}</p>
        </div>
        <div class="f-cell">
          <p>IMEI号</p>
          <p>{{formData.imei || '--'}}</p>
        </div>
      </section>

      <section class="f-meal-box">
        <p class="f-title">已订套餐/加油包</p>
        <section class="f-residual-flow-card" v-for="(item, index) in cardPackList" :key="index"
          :style="{'background': !item.isUsed? '#EAE9F3': ''}" @click="toPack('/meal/pack',item)">
          <p class="f-name">
            <span>{{item.title || '--'}}</span>
            <span v-if="item.isUsed">（{{item.enableIsp}}）</span>
          </p>
          <p v-if="item.isUsed" class="f-time">{{item.startdate }} 至 {{ item.enddate}}有效</p>
          <img v-if="!item.isUsed" class="f-unenforced" src="@/assets/icons/icon_labe_unenforced.png" alt="">
          <img v-if="item.isUsed" class="f-more-img" src="@/assets/icons/more_btn_enter.png" alt="">
          <template v-if="item.addiInfoList">
            <div class="f-pack" v-for="(myItem,myIndex) in item.addiInfoList" :key="myIndex">
              <p>{{ myItem.title }}</p>
              <p v-if="myItem.isUsed">{{myItem.startdate }} 至 {{ myItem.enddate}}有效</p>
              <p v-else>未生效</p>
            </div>
          </template>
        </section>
        <p v-if="!cardPackList.length" class="f-center f-mb-10">暂无套餐/加油包</p>
      </section>

      <section class="f-opeartion-box">
        <p class="f-title">其它功能</p>
        <ul class="f-ul">
          <li @click="pageJump('/inChina/internetRecord')">
            <img src="@/assets/icons/icon_traffic_billing.png" alt="">
            <p>流量账单</p>
          </li>
          <li @click="pageJump('/inChina/rechargeRecord')">
            <img src="@/assets/icons/icon_recharge_record.png" alt="">
            <p>订购记录</p>
          </li>
          <!-- <li @click="popup =true">
            <img src="@/assets/icons/icon_unbound.png" alt="">
            <p>解除绑定</p>
          </li> -->
        </ul>
      </section>
    </van-pull-refresh>

    <van-popup v-model:show="popup" position="bottom" round class="f-popup">
      <p class="f-title">切网成功</p>
      <p>通常需要30秒以上完成驻网过程 请耐心等待</p>
      <div class="f-btn">
        <van-button style="width: 150px;" type="primary" block round @click="popup = false">我知道了</van-button>
      </div>
    </van-popup>
  </section>
</template>
  
<script>
import { ref, reactive, toRefs, onMounted, watch, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import api from '../api'
import { successDeal, bytesToSize, getDateTime, setStore, getJoinDate, getStore, errorDeal } from '@/utils/utils';
import JsBridge from '@/utils/JsBridge.js'
import { showLoadingToast, closeToast, showToast, showDialog } from 'vant';

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const state = reactive({
      formData: getStore('cardInfo') || {},
      cardPackList: getStore('cardInfo') ? getStore('cardInfo').cardPackList ? getStore('cardInfo').cardPackList : [] : [],

      priority: {
        'base': '单次包',
        'month': '每月包',
        'rate': '累计包',
        'quicken': '提速包',
        'addi': '加油包',
        'holiday': '假日包',
      },

      popup: false,

      isConnect: false,
      currentIccid: "",
      currentOperatorName: "",
      operatorName: {
        'CUC': '中国联通',
        'CMC': '中国移动',
        'CTC': '中国电信',
        // '46000': '中国移动',
        // '46002': '中国移动',
        // '46004': '中国移动',
        // '46007': '中国移动',
        // '46008': '中国移动',
        // '46009': '中国移动',
        // '46024': '中国移动',
        // '45400': '优客联',
        // '45412': '优客联',
        // '45413': '优客联',
        // '45415': '优客联',
        // '45417': '优客联',
        // '46003': '中国电信',
        // '46005': '中国电信',
        // '46011': '中国电信',
        // '46001': '中国联通',
        // '46006': '中国联通',
      },
      ispName: {
        'unicom': '中国联通',
        'cmcc': '中国移动',
        'telecom': '中国电信',
        'cbn': '中国广电',
      },

      refreshing: false,
      timer: null,
      currentIsp: {},
      isChangeOperator: false,
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '国内服务详情',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
        bg: ''
      });

      // 获取设备的消息
      JsBridge.registerHandler("onSocketMessage", function (response, responseCallback) {
        let data = JSON.parse(response)
        console.log(data, route.path)
        if (route.path == '/inChina') {
          clearTimeout(state.timer)
          if (data) {
            switch (data.msg) {
              case 'connect':
                if (data.state) {
                  console.log('设备连接成功')
                  if (!state.isConnect) {
                    closeToast()
                    getDevImei()
                  }
                  state.isConnect = true
                } else {
                  closeToast()
                  state.isConnect = false
                  console.log('设备连接已关闭')
                }
                break
              case 'checkChangeOperator':
                if (data.data.state) {
                  changeOperator(state.currentIsp)
                } else {
                  errorDeal('频繁切网，请稍后尝试')
                }
                break;
              case 'changeOperatorByIndex':
                closeToast()
                if (data.data.state) {
                  state.isChangeOperator = true
                  showLoadingToast({
                    message: '切换运营商中...',
                    forbidClick: true,
                    duration: 0,
                  });
                  setTimeout(() => {
                    getIccid()
                  }, 1000 * 15)
                } else {
                  if (data.data.code == '-101') {
                    errorDeal('频繁操作，请稍后尝试')
                  } else {
                    errorDeal('切换运营商失败')
                  }
                }
                break
              case 'getDevImei':
                closeToast()
                if (data.data.imei1 == state.formData.imei || data.data.imei2 == state.formData.imei) {
                  getIccid()
                } else {
                  showDialog({
                    title: '连接异常',
                    message: '当前设备不匹配',
                  }).then(() => {
                    closeDevice()
                  });
                }
                break
              case 'getIccid':
                console.log(data.data, state.formData)
                closeToast()
                if (data.data.state) {
                  let newIccid = data.data.iccid.slice(0, 13)
                  console.log('newIccid', newIccid)

                  let inChinaIccidList = []
                  state.formData.cardIspList.forEach(item => {
                    inChinaIccidList.push(item.iccid.slice(0, 13))
                  })
                  console.log('inChinaIccidList', inChinaIccidList)

                  let findIndexInChina = inChinaIccidList.findIndex(item => item == newIccid)
                  if (findIndexInChina > -1) {
                    let findIndex = state.formData.cardIspList.findIndex(item => item.iccid == data.data.iccid)
                    if (findIndex > -1) {
                      // checkSimUserCode()
                      if (state.isChangeOperator) {
                        state.popup = true
                        state.isChangeOperator = false
                      }
                      state.currentOperatorName = state.formData.cardIspList[findIndex].isp
                    } else {
                      showDialog({
                        title: '连接异常',
                        message: '当前sim卡不匹配',
                      }).then(() => {
                        closeDevice()
                      });
                    }
                  } else {
                    state.currentOperatorName = ''
                  }
                } else {
                  showDialog({
                    title: '连接异常',
                    message: '当前sim卡不可用',
                  }).then(() => {
                    closeDevice()
                  });
                }
                break
              case 'checkSimUserCode':
                closeToast()
                if (!data.data.result) {
                  showDialog({
                    title: '连接异常',
                    message: '当前sim卡不可用',
                  }).then(() => {
                    closeDevice()
                  });
                }
                break;
            }
          }
        }
      });

      getCardInfo()
      // openDevice()
      // getPackcardInfo()
    })

    const getCardInfo = () => {
      api.cardInfo({ code: route.query.code }).then(res => {
        state.formData = res.data
        if (res.data && res.data.cardPackList) {
          state.cardPackList = res.data.cardPackList
        }
      })
    }

    const getPackcardInfo = () => {
      let json = {
        code: route.query.code
      }
      api.packcardInfo(json).then(res => {
        console.log(res.data)
      })
    }

    function handleCopy(value) {
      const input = document.createElement('input');
      document.body.appendChild(input);
      input.setAttribute('value', value);
      input.select();
      if (document.execCommand('copy')) {
        document.execCommand('copy');
        successDeal('复制成功')
      }
      document.body.removeChild(input);
    }

    // 开启设备连接
    const openDevice = () => {
      showLoadingToast({
        message: '设备连接中...',
        forbidClick: true,
        duration: 0,
      });
      state.timer = setTimeout(() => {
        errorDeal('设备连接失败')
      }, 1000 * 5)
      JsBridge.callHandler('connect', {}, (response) => {
        let data = JSON.parse(response)
        console.log('connect', data)
      })
    }

    // 关闭设备连接
    const closeDevice = () => {
      state.isConnect = false
      JsBridge.callHandler('disConnect', {}, (response) => { })
    }

    // 检查是否可以切换运营商
    const checkChangeOperator = (parmary) => {
      if (parmary.isRealName != 1) {
        router.push({
          path: '/realName',
          query: {
            isp: parmary.isp,
            url: parmary.url
          }
        })
        return
      }
      if (!state.isConnect) {
        errorDeal('请先连接设备')
        return
      }
      state.currentIsp = parmary
      let msgId = `checkChangeOperator-${new Date().getTime()}`
      JsBridge.callHandler('checkChangeOperator', msgId, (response) => { })
    }

    // 切换运营商 
    const changeOperator = (parmary) => {
      showLoadingToast({
        message: '切换运营商中...',
        forbidClick: true,
        duration: 0,
      });
      state.timer = setTimeout(() => {
        errorDeal('切换运营商失败')
      }, 1000 * 5)

      if (state.ispName[state.currentOperatorName] == state.ispName[parmary.isp]) {
        errorDeal(`当前服务已是${state.ispName[parmary.isp]}`)
        return
      }
      let index = parmary.cardSlot
      let timestamp = new Date().getTime()
      let json = {
        index,
        msgId: ''
      }
      JsBridge.callHandler('changeOperatorByIndex', json, (response) => {
        let data = JSON.parse(response)
        console.log('changeOperatorByIndex', data)
      })
    }

    // 获取设备的iccic
    const getIccid = () => {
      let json = {
        msgId: ''
      }
      JsBridge.callHandler('getIccid', json, (response) => {
        let data = JSON.parse(response)
      })
    }

    // 获取当前运营商
    const getOperatorName = () => {
      let json = {
        msgId: ''
      }
      JsBridge.callHandler('getOperatorName', json, (response) => {
        let data = JSON.parse(response)
      })
    }

    // 获取设备Imei
    const getDevImei = () => {
      let json = {
        msgId: ''
      }
      JsBridge.callHandler('getDevImei', json, (response) => {
        let data = JSON.parse(response)
      })
    }

    // 是否是全讯的卡
    const checkSimUserCode = () => {
      let json = {
        userCode: state.formData.code,
        msgId: ''
      }
      JsBridge.callHandler('checkSimUserCode', json, (response) => {
        let data = JSON.parse(response)
        console.log('checkSimUserCode', data)
      })
    }

    // 解除绑定
    const handleUnbind = () => {
      let json = {
        code: route.query.code
      }
      api.unbind(json).then(res => {
        successDeal('已解除绑定')
        setTimeout(() => {
          router.go(-1)
        }, 500);
      })
    }

    const pageJump = (path) => {
      setStore('CURRENT_CODE', { code: route.query.code })
      router.push({
        path,
        query: {
          flag: true,
          code: route.query.code,
          mealType: 1,
        }
      })
    }

    const toPack = (path, data) => {
      if (!data.isUsed) return
      setStore('CURRENT_CODE', { code: route.query.code })
      setStore('CURRENT_MEAL', data)
      router.push({
        path,
        query: {
          flag: true,
          code: route.query.code,
          mealType: 1,
        }
      })
    }

    const onRefresh = () => {
      getCardInfo()
      getIccid()

      if (state.refreshing) {
        state.refreshing = false;
      }
    };

    onBeforeUnmount(() => {
      closeDevice()
    })

    return {
      ...toRefs(state),
      bytesToSize,
      getDateTime,
      getJoinDate,
      openDevice,
      closeDevice,
      handleCopy,
      pageJump,
      handleUnbind,
      changeOperator,
      onRefresh,
      toPack,
      checkChangeOperator,
    }
  }
}
</script>
  
<style lang='scss' scoped>
.f-card-detail {
  padding: 14px;
  display: flex;
  flex-direction: column;
  .f-phone-box {
    margin-left: 2px;
    background-image: url("@/assets/imgs/pic_bg_details.png");
    background-size: 100% 100%;
    width: 344px;
    height: 137px;
    padding: 14px 19px 0 19px;
    position: relative;
    .f-iccid {
      font-weight: 400;
      font-size: 16px;
      color: #ffffff;
      img {
        width: 14px;
        height: 14px;
        margin-left: 10px;
      }
    }
    .f-box {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-top: 16px;
      margin-left: 1px;
      .f-flow {
        font-weight: 500;
        font-size: 16px;
        color: #fefefe;
      }
    }
    .f-btn-box {
      position: absolute;
      left: 0;
      bottom: 7px;
      width: 337px;
      height: 34px;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 0 0 6px 6px;
      p {
        text-align: center;
        line-height: 34px;
        font-weight: 400;
        font-size: 13px;
        color: #ffffff;
        text-align: center;
      }
    }
  }
  .f-network-box {
    width: 347px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 13px;
    padding-bottom: 19px;
    margin-top: 13px;
    .f-title {
      font-weight: 400;
      font-size: 14px;
      color: #000000;
      padding: 17px 13px 16px 14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .f-ul {
      position: relative;
      display: flex;
      align-items: center;
      margin: 0 17px 14px 17px;
      .f-li {
        width: 98px;
        height: 54px;
        border-radius: 3px;
        border: 1px dashed #666666;
        padding: 10px 0px 6px 0px;
        font-weight: 500;
        font-size: 12px;
        color: #000000;
        .f-img {
          width: 16px;
          height: 16px;
          margin-left: 14px;
        }
        .f-real-name {
          background: #fd6a56;
          border-radius: 8px;
          font-weight: 400;
          font-size: 9px;
          color: #ffffff;
          text-align: center;
          padding: 1px 6px;
        }
      }
      .f-li-active {
        border: 1px dashed #304eee !important;
      }
      .f-li:not(:first-child) {
        margin-left: 10px;
      }
      .f-arrows {
        position: absolute;
        width: 100%;
        left: 0;
        top: 0;
        // transform: translateY(-50%);
        img {
          width: 5px;
          height: 9px;
        }
        .f-img-box01 {
          position: absolute;
          left: -18px;
          height: 55px;
          width: 17px;
          line-height: 55px;
          text-align: center;
        }
        .f-img-box02 {
          position: absolute;
          right: -15px;
          height: 55px;
          width: 15px;
          line-height: 55px;
          text-align: center;
        }
      }
    }
    .f-cell {
      font-weight: 400;
      font-size: 12px;
      color: #424242;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px 13px 0px 14px;
    }
    .f-connected-box {
      padding: 6px 11px;
      font-size: 11px;
      background: rgba(255, 255, 255, 0.3);
      border: 1px solid red;
      border-radius: 11px;
      display: flex;
      align-items: center;
      img {
        width: 11px;
        height: 11px;
        margin-right: 5px;
      }
    }
  }
  .f-meal-box {
    width: 347px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 13px;
    margin-top: 13px;
    padding-bottom: 8px;
    .f-title {
      font-weight: 400;
      font-size: 14px;
      color: #000000;
      padding: 17px 0 16px 14px;
    }
    .f-residual-flow-card {
      width: 317px;
      background: #cad9ff;
      border-radius: 13px;
      padding: 18px 10px 11px 10px;
      margin-left: 15px;
      margin-bottom: 9px;
      position: relative;
      .f-name {
        font-weight: 400;
        font-size: 14px;
        color: #424242;
        margin-bottom: 8px;
        padding-left: 10px;
      }
      .f-chart {
        width: 275px;
        height: 5px;
        background: #e2e1e1;
        border-radius: 6px;
        position: relative;
        margin: 3px 0 3px 0;
        .f-chart-inner {
          content: "";
          position: absolute;
          left: 0;
          top: 0;
          height: 5px;
          border-radius: 6px;
          background: linear-gradient(90deg, #c6379c, #3c65aa);
        }
      }
      .f-box-01 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: 300;
        font-size: 8px;
        color: #666666;
      }
      .f-box-02 {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: 500;
        font-size: 12px;
        color: #000000;
      }
      .f-time {
        font-weight: 300;
        font-size: 11px;
        color: #666666;
        padding-left: 10px;
      }
      .f-unenforced {
        width: 59px;
        height: 19px;
        position: absolute;
        top: 0;
        right: 0;
      }
      .f-more-img {
        position: absolute;
        right: 15px;
        top: 30px;
        width: 7px;
      }
      .f-pack {
        width: 100%;
        background: #e9efff;
        border-radius: 13px;
        padding: 14px 0 15px 10px;
        font-weight: 400;
        font-size: 12px;
        color: #345abb;
        margin-top: 20px;
        p:last-child {
          font-weight: 300;
          font-size: 10px;
          color: #666666;
          margin-top: 5px;
        }
      }
    }
  }
  .f-device-box {
    width: 347px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 13px;
    margin-top: 13px;
    padding-bottom: 8px;
    font-weight: 400;
    font-size: 12px;
    color: #424242;
    padding: 12px 13px 25px 14px;
    .f-title {
      font-weight: 400;
      font-size: 14px;
      color: #000000;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15px;
      .f-btn-box {
        width: 71px;
        background: #304eee;
        border-radius: 14px;
        font-weight: 400;
        font-size: 11px;
        color: #ffffff;
        text-align: center;
        padding: 5px 0;
      }
    }
  }
  .f-opeartion-box {
    width: 347px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 13px;
    margin-top: 13px;
    padding-bottom: 8px;
    .f-title {
      font-weight: 400;
      font-size: 14px;
      color: #000000;
      padding: 17px 0 16px 14px;
    }
    .f-ul {
      display: flex;
      align-items: center;
      li {
        font-weight: 500;
        font-size: 13px;
        color: #000000;
        text-align: center;
        width: 100px;
        img {
          width: 43px;
          height: 43px;
          margin-bottom: 5px;
        }
      }
    }
  }
  .f-popup {
    font-weight: 400;
    font-size: 14px;
    color: #666666;
    text-align: center;
    padding: 53px 25px 42px 25px;
    .f-title {
      font-size: 16px;
      color: #000000;
      margin-bottom: 20px;
    }
    .f-btn {
      display: flex;
      justify-content: center;
      margin-top: 40px;
    }
  }
}
</style>